<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目" prop="subject">
        <el-select v-model="queryParams.subject" placeholder="请选择科目" clearable filterable>
          <el-option
            v-for="dict in dict.type.t_subject"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:videos:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="名称" align="center" prop="fileName"/>
      <el-table-column label="视频格式" align="center" prop="fileFormat"/>
      <el-table-column label="视频大小" align="center" prop="fileSize">
        <template slot-scope="scope">
          <span>{{ scope.row.fileSize | filterType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="视频说明" align="center" prop="resRemake"/>
      <el-table-column label="科目" align="center" prop="subject">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.t_subject" :value="scope.row.subject"/>
        </template>
      </el-table-column>
      <el-table-column label="视频封面" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="previewAndDownload(scope.row)"
          >播放视频
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:videos:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:videos:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入课程名称"/>
        </el-form-item>
        <el-form-item label="视频说明" prop="resRemake">
          <el-input v-model="form.resRemake" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择科目" filterable>
            <el-option
              v-for="dict in dict.type.t_subject"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频封面" prop="cover">
          <image-upload v-model="form.cover" :limit="1"/>
        </el-form-item>
        <el-form-item label="上传视频" prop="contentSize">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".mp4"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-exceed="handleExceed"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :before-remove="beforeRemove"
          >
            <el-button slot="trigger" size="small" type="primary">选取视频</el-button>
            <div slot="tip" class="el-upload__tip">
              可上传.mp4格式视频，且不超过500M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    视频预览-->
    <el-dialog :title="videoDialog.title" :visible.sync="videoDialog.open" width="800px" append-to-body
               :before-close="handleClose">
      <div>
        <VideoPlay
          ref="video"
          v-show="true"
          :videoUrl="videoUrl"
          :videoCover="videoCover"
          :width="760"
          :height="450"
          :autoplay="true"
          :controls="true"
          :loop="false"
          :muted="false"
          preload="auto"
          :showPlay="true"
          :playWidth="96"
          zoom="cotain"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listVideos, getVideos, delVideos, addVideos, updateVideos, getBlobByFileId} from "@/api/business/videos";
import {getToken} from "@/utils/auth";
import VideoPlay from '@/components/video/VideoPlay';

export default {
  name: "Videos",
  dicts: ['t_subject'],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videosList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        fileName: null,
        fileFormat: null,
        fileSize: null,
        resRemake: null,
        subject: null,
        cover: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fileName: [
          {required: true, message: "视频名不能为空", trigger: "blur"}
        ],
        fileFormat: [
          {required: true, message: "视频格式不能为空", trigger: "blur"}
        ],
        fileSize: [
          {required: true, message: "视频大小不能为空", trigger: "blur"}
        ],
        resRemake: [
          {required: true, message: "视频说明不能为空", trigger: "blur"}
        ],
        subject: [
          {required: true, message: "科目不能为空", trigger: "change"}
        ],
        cover: [
          {required: true, message: "视频封面不能为空", trigger: "blur"}
        ],
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的视频列表
        fileList: [],
        fileId: null
      },
      //视频预览弹框
      videoDialog: {
        title: '播放视频',
        open: false,
        imgSrc: [],
      },
      videoUrl: null,
      // 视频封面支持https或require本地地址
      videoCover: require('@/assets/files/Bao.jpg'),
    };
  },
  components: {
    VideoPlay
  },
  filters: {
    /**
     * 视频大小格式化
     * @param val
     * @returns {string}
     */
    filterType: function (val) {
      if (val === 0) return "0 B"
      var k = 1024;
      var sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(val) / Math.log(k));
      return (val / Math.pow(k, i)).toPrecision(3) + "" + sizes[i]

    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true;
      listVideos(this.queryParams).then(response => {
        this.videosList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileId: null,
        fileName: null,
        fileFormat: null,
        fileSize: null,
        resRemake: null,
        subject: null,
        cover: null,
      };
      this.upload.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVideos(id).then(response => {
        this.form = response.data;
        if (response.data.sysFileInfo != null && response.data.sysFileInfo != undefined) {
          this.form.outlineId = response.data.sysFileInfo.fileId;
          let file = {"name": response.data.sysFileInfo.fileName, "url": response.data.sysFileInfo.filePath};
          this.upload.fileList.push(file);
        }
        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideos(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideos(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除视频编号为"' + ids + '"的数据项？').then(function () {
        return delVideos(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/videos/export', {
        ...this.queryParams
      }, `videos_${new Date().getTime()}.xlsx`)
    },
    // 视频上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 视频上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.fileId = response.fileId;
      this.upload.fileId = response.fileId;
      this.form.fileFormat = response.fileFormat;
      this.form.fileSize = response.fileSize;
      // this.$modal.msgSuccess(response.msg);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多选择 1 个视频`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /**
     * 课件预览
     */
    previewAndDownload(row) {
      this.showVideo(row.fileId);
    },
    /**
     * 视频播放
     * @param id
     */
    showVideo(id) {
      this.videoDialog.open = true;
      getBlobByFileId(id).then(data => {
        const blob = new Blob([data], {type: 'image/png'})
        const url = window.URL.createObjectURL(blob)
        this.videoUrl = url
      })
    },
    handleClose() {
      this.$refs.video.zanting();
      this.videoDialog.open = false;
    }
  },
};
</script>
